package cn.ruituo.web;

import cn.ruituo.entity.Grade2;
import cn.ruituo.vo.Page;
import cn.ruituo.entity.Student;
import cn.ruituo.service.GradeService;
import cn.ruituo.service.StudentService;
import cn.ruituo.util.LogUtil;
import cn.ruituo.vo.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@Controller
@RequestMapping("student")
@CrossOrigin
public class StudentController {

    @Value("${myschool.uploadpath}")
    private String path;

    @Autowired
    private StudentService studentService;

    @Autowired
    private GradeService gradeService;

   /* public void pagAjax(HttpServletResponse resp){
        Page p=null;
        String str="";
        resp.getWriter().print(str);
    }*/



   @ApiOperation(value = "学生查询",code = 200)
   @ApiResponses(@ApiResponse(code=200,message = "{'datas':'返回数据','totalLines':'总数','totalPages':'总页数，计算出来的','pageNo':'当前页号','pageSize':'页大小'}"))
    @GetMapping(value = "pageAjax", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public Page<Student> paging2(@ApiParam("页号，默认为1") @RequestParam(name = "page", defaultValue = "1") int pageNo, @ApiParam("页大小，默认为10")@RequestParam(name = "limit", defaultValue = "10") int pageSize, @ApiParam("学生姓名，可以不填")@RequestParam(name = "sname", required = false) String sname, @RequestParam(name = "qq", required = false) String qq
            , @RequestParam(name = "telephone", required = false) String telephone, @RequestParam(name = "enterDateStart", required = false) Date start
            , @RequestParam(name = "enterDateEnd", required = false) Date end
    ) {
       // return null;
        LogUtil.info("This is ajax paging");
        Page<Student> paging = this.studentService.paging(pageNo, pageSize, sname, qq, telephone, start, end
        );
        return paging;
    }

    @ResponseBody
    @RequestMapping(value = "checkPhone",produces = "application/json;charset=utf-8")
    public Result checkPhone(@RequestParam("phone") String phone) {
        boolean b = this.studentService.checkPhone(phone);
        return b?Result.success("手机已经被使用了"):Result.error("手机号可以使用");
    }
    @ResponseBody
    @GetMapping("get/{stuno}")
    @ApiOperation("根据学号获得学生信息")
    public Result get(@ApiParam("学号，采用rest的参数格式") @PathVariable long stuno) {
        Student st = this.studentService.get(stuno);
        return st == null ? Result.error("学生信息不存在") : Result.success(st);
    }

    //    @ResponseBody
//    @GetMapping("get/{stuno}")
//    public Student get(@PathVariable  long stuno){
//        return this.studentService.get(stuno);
//    }
//    @ResponseBody
//    @GetMapping(delete/"{stuno}")
//    public int del(@PathVariable  long stuno){
//        return this.studentService.del(stuno);
//    }
    @ResponseBody
    @GetMapping("delete/{stuno}")
    public Result del(@PathVariable long stuno) {
        return this.studentService.del(stuno) > 0 ? Result.success("删除成功") : Result.error("删除失败！");
    }



    @PostMapping("add")//{}
    @ResponseBody
    public Result add(Student student, @RequestPart(name = "file", required = false) MultipartFile idcard) throws IOException {
        LogUtil.info(">>>>>>>>>>>>,{}"+student+",文件："+idcard);
        if(idcard!=null)
            LogUtil.info(idcard.getOriginalFilename()+","+idcard.getSize());
        if (idcard!=null&& idcard.isEmpty() == false) {
            String oldName = idcard.getOriginalFilename();
            String suffix = oldName.substring(oldName.lastIndexOf('.'));
            String newName = UUID.randomUUID() + suffix;
            //String path = req.getServletContext().getRealPath("images");
            File f = new File(path+"/images");
            LogUtil.info(f.getAbsoluteFile());
            if (!f.exists())
                f.mkdirs();
            idcard.transferTo(new File(f, newName));
            student.setIdcardpic(newName);
        }

        int r = this.studentService.add(student);

        return  r>0?Result.success("增加新生成功"):Result.error("更新失败");
    }


    @PostMapping("update")//{}
    @ResponseBody
    public Result update(@Valid @ModelAttribute Student student, @RequestPart(name = "idcard", required = false) MultipartFile idcard, HttpServletRequest req) throws IOException {

        if (idcard.isEmpty() == false) {
            String oldName = idcard.getOriginalFilename();
            String suffix = oldName.substring(oldName.lastIndexOf('.'));
            String newName = UUID.randomUUID() + suffix;
            //String path = req.getServletContext().getRealPath("images");
            File f = new File(path+"/images");
            LogUtil.info(f.getAbsoluteFile());
            if (!f.exists())
                f.mkdirs();
            idcard.transferTo(new File(f, newName));
            student.setIdcardpic(newName);
        }
        int r = this.studentService.update(student);

        return  r>0?Result.success():Result.error("更新失败");
    }
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        //特殊化
        binder.registerCustomEditor(Date.class, "birthday", new CustomDateEditor(dateFormat2, true));
    }
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handler(Exception e) {
        LogUtil.info(e.getClass().getName());
        LogUtil.error("出错了", e);
        return Result.error(406,e.getMessage());
        //return Result.error(406,"出错了。。。");
    }
    @ExceptionHandler(BindException.class)
    public String handler2(Exception e, BindingResult result,Model model) {
        //if(result.hasErrors()){
        for (FieldError error : result.getFieldErrors()) {
            model.addAttribute(error.getField(), error.getDefaultMessage());
        }

        LogUtil.error("出错了", e);

        //}
        return "forward:/student/toAdd";
    }
//    @ExceptionHandler(Exception.class)
//    public String handler(Exception e) {
//        LogUtil.error(e.getMessage(), e);
//        return "forward:/error.jsp";
//    }

    @GetMapping("download")
    public Result download(HttpServletResponse response)throws ServletException, IOException{
            byte b[]=new byte[26];
            Arrays.fill(b,(byte)'a');
            //b[233]='f';
            String fileName="26个字母.txt";
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(fileName,"utf-8") + "\"");
            ServletOutputStream out = response.getOutputStream();
            //输出
            out.write(b);
            out.flush();
            return Result.success();
        }

}